package com.rzico.sbl.ui.mine

import com.amap.api.services.core.PoiItem
import com.jeremyliao.liveeventbus.LiveEventBus
import com.lzy.okgo.model.HttpMethod
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityShopModifyBinding
import com.rzico.sbl.model.BaseUrl
import com.rzico.sbl.model.RegionBean
import com.rzico.sbl.other.showAreaDialog
import com.rzico.sbl.ui.member.MemberAdressAddActivity
import com.rzico.sbl.viewmodel.ShopViewModel
import com.xinnuo.common.extend.*
import com.xinnuo.common.helper.*
import com.xinnuo.common.other.NameLengthFilter
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.common_ui.utils.clear
import org.json.JSONObject

class ShopModifyActivity : BaseActivity(R.layout.activity_shop_modify) {

    private val mBinding by lazy {
        ActivityShopModifyBinding.bind(getRootView())
    }

    private val mAreaList = arrayListOf<RegionBean>()
    private lateinit var mStatus: String
    private var mShopId = ""
    private var mAreaId = ""
    private var mAreaCode = ""
    private var mLat = 0.0
    private var mLng = 0.0

    override fun getViewModel() = get<ShopViewModel>()

    override fun initData() {
        initTitle(title = intent.getExtra("title"))

        when (mStatus) {
            "add", "open" -> mBinding.shopSave.text = "确认添加"
            "edit" -> mShopId.notEmpty { getData() }
        }
    }

    override fun initListener() {
        mShopId = intent.getExtra("shopId")
        mStatus = intent.getExtra("status")

        mBinding.apply {
            shopName.filters = arrayOf(NameLengthFilter(20))

            // 省市区选择
            shopArea.oneClick {
                mAreaList
                    .isNotEmpty()
                    .conditionElse(
                        actionTrue = ::showBottomArea,
                        actionFalse = {
                            getViewModel()
                                .getAreaList {
                                    mAreaList.addItems(it)

                                    showBottomArea()
                                }
                        }
                    )
            }

            // 地图选点
            shopAreaMap.oneClick {
                startActivityEx<MemberAdressAddActivity>()
            }

            // 保存编辑
            shopSave.oneClick {
                when {
                    shopTitle.textTrim.isEmpty() -> {
                        showToast("请输入店铺名称")
                        shopTitle.requestFocus()
                        return@oneClick
                    }

                    shopName.textTrim.isEmpty() -> {
                        showToast("请输入联系姓名")
                        shopName.requestFocus()
                        return@oneClick
                    }

                    shopPhone.content.isEmpty() -> {
                        showToast("请输入联系电话")
                        shopPhone.requestFocus()
                        return@oneClick
                    }

                    shopArea.content.isEmpty() -> {
                        showToast("请选择所在地区")
                        return@oneClick
                    }

                    shopDetail.textTrim.isEmpty() -> {
                        showToast("请输入详细地址")
                        shopDetail.requestFocus()
                        return@oneClick
                    }

                    !shopPhone.content.isTel()
                            && !shopPhone.content.isVirtual() -> {
                        showToast("请输入正确的联系电话")
                        shopPhone.requestFocus()
                        return@oneClick
                    }
                }

                getViewModel()
                    .request(
                        requestUrl = BaseUrl.shopAdd,
                        isMultipart = true,
                        params = arrayOf(
                            "id" to mShopId,
                            "name" to shopTitle.textTrim,
                            "categoryId" to 1,
                            "linkman" to shopName.textTrim,
                            "telephone" to shopPhone.content,
                            "areaId" to mAreaId,
                            "areaCode" to mAreaCode,
                            "address" to shopDetail.textTrim,
                            "lat" to mLat,
                            "lng" to mLng,
                            "printerS" to shopCount.content,
                            "sleepInterval" to shopSpace.content,
                        ),
                        onSuccess = {
                            when (mStatus) {
                                "open" -> showToast("店铺信息提交成功，请等待管理员审核！")
                                "add" -> showToast("添加店铺成功！")
                                "edit" -> showToast("店铺修改成功！")
                            }

                            // 刷新店铺列表
                            when (mStatus) {
                                "open" -> {
                                    val obj = JSONObject(it)

                                    LiveEventBus
                                        .get("shopOpen")
                                        .post(obj.optNotNull("id"))
                                }

                                else -> LiveEventBus.get("shopList").post("refresh")
                            }

                            finishView()
                        }
                    )
            }
        }

        // 地图选点监听
        LiveEventBus
            .get("adressAdd", PoiItem::class.java)
            .observe(this) {
                mLat = it.latLonPoint.latitude
                mLng = it.latLonPoint.longitude
                mAreaId = ""
                mAreaCode = it.adCode

                mBinding.apply {
                    shopArea.text = "${it.provinceName} ${it.cityName} ${it.adName}"
                    shopDetail.setText(it.snippet + it.title)
                    shopDetail.setSelection(shopDetail.text.length)
                }
            }
    }

    /**
     * 省市区弹框
     */
    private fun showBottomArea() {
        showAreaDialog(
            title = "请选择地区",
            list = mAreaList,
            listener = { pname, cname, aname, _, _, adcode ->
                mBinding.apply {
                    mLat = 0.0
                    mLng = 0.0
                    mAreaId = ""
                    mAreaCode = adcode

                    shopArea.text = "$pname $cname $aname"
                    shopDetail.clear()
                }
            }
        )
    }

    /**
     * 店铺详情
     */
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .request(
                requestUrl = BaseUrl.shopDet,
                requestMethod = HttpMethod.GET,
                params = arrayOf("shopId" to mShopId),
                onSuccess = {
                    val obj = JSONObject(it)

                    mBinding.apply {
                        mAreaId = obj.optNotNull("areaId")
                        mLat = obj.optNotNull("lat").doubleValue
                        mLng = obj.optNotNull("lng").doubleValue

                        shopTitle.setText(obj.optNotNull("name"))
                        shopName.setText(obj.optNotNull("linkman"))
                        shopPhone.setText(obj.optNotNull("telephone"))
                        shopArea.text = obj.optNotNull("areaName")
                        shopDetail.setText(obj.optNotNull("address"))
                        shopCount.setText(obj.optNotNull("s"))
                        shopSpace.setText(obj.optNotNull("sleepInterval"))
                    }
                }
            )
    }

}